package com.example.king.openglenvdemo;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;

import com.example.king.glutils.GlesUtil;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import static android.opengl.GLES20.*;

/**
 * 画一个点--改变颜色
 */
public class ColorPointRenderer implements GLSurfaceView.Renderer {

    private final String mVertexShader =
            "attribute vec4 aPosition;\n" +
            "void main() {\n" +
            "  gl_Position = aPosition;\n" +
            "  gl_PointSize = 30.0;\n" +
            "}\n";

    private final String mFragmentShader =
            "precision mediump float;\n" +
            "uniform vec4 u_FragColor;\n" +
            "void main() {\n" +
            "  gl_FragColor = u_FragColor;\n" +
            "}\n";

    private int mProgram;

    private int maPositionHandle;
    private int muFragColorHandle;

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        mProgram = GlesUtil.linkProgram(mVertexShader, mFragmentShader);
        glUseProgram(mProgram);

        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

        maPositionHandle = glGetAttribLocation(mProgram, "aPosition");
        GlesUtil.catchError("aPosition");

        muFragColorHandle = glGetUniformLocation(mProgram, "u_FragColor");
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        glViewport(0, 0, width, height);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        glClear(GL_COLOR_BUFFER_BIT);

        glVertexAttrib3f(maPositionHandle, 0.0f, 0.9f, 0.0f);
        glUniform4f(muFragColorHandle, 1.0f, 0.0f, 0.0f, 1.0f);

        glDrawArrays(GLES20.GL_POINTS, 0, 1);
    }
}
